package com.train.user.controller;

import com.train.common.core.controller.BaseController;
import com.train.common.core.domain.AjaxResult;
import com.train.user.domain.SysPostLike;
import com.train.user.service.SysPostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import com.train.common.core.domain.model.LoginUser;
import com.train.common.utils.SecurityUtils;

/**
 * 动态点赞管理 控制器
 * 
 * @author train
 */
@RestController
@RequestMapping("/user/post/like")
public class SysPostLikeController extends BaseController {

    @Autowired
    private SysPostLikeService sysPostLikeService;

    /**
     * 点赞动态
     * @param postId 动态ID
     * @return 结果
     */
@PostMapping("/like")
public AjaxResult likePost(@RequestParam Long postId) {
    try {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return AjaxResult.error("用户未登录");
        }
        
        Long userId = loginUser.getUserId();
        boolean result = sysPostLikeService.likePost(userId, postId);
        return AjaxResult.success(result ? "点赞成功" : "您已经点赞过了");
    } catch (IllegalArgumentException e) {
        return AjaxResult.error(e.getMessage());
    } catch (RuntimeException e) {
        return AjaxResult.error(e.getMessage());
    } catch (Exception e) {
        logger.error("点赞失败", e);
        return AjaxResult.error("系统错误，请稍后重试");
    }
}

    /**
     * 取消点赞动态
     * @param postId 动态ID
     * @return 结果
     */
    @PostMapping("/cancel")
    public AjaxResult cancelLikePost(@RequestParam Long postId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        
        boolean result = sysPostLikeService.cancelLikePost(userId, postId);
        if (result) {
            return AjaxResult.success("取消点赞成功");
        } else {
            return AjaxResult.error("取消点赞失败");
        }
    }

    /**
     * 检查用户是否点赞了动态
     * @param postId 动态ID
     * @return 结果
     */
    @GetMapping("/check")
    public AjaxResult checkLike(@RequestParam Long postId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        
        boolean isLiked = sysPostLikeService.isPostLikedByUser(userId, postId);
        return AjaxResult.success().put("isLiked", isLiked);
    }

    /**
     * 获取动态的点赞列表
     * @param postId 动态ID
     * @return 结果
     */
    @GetMapping("/list/{postId}")
    public AjaxResult getLikeList(@PathVariable Long postId) {
        List<SysPostLike> likeList = sysPostLikeService.getLikesByPostId(postId);
        return AjaxResult.success(likeList);
    }
}
